﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using Frame;
using System.IO;
using System.Xml;
using System.Threading;

namespace AdtMotion
{
    public partial class MainFrm : Form
    {
        private Global g_Global;    //全局变量
        private NotifyIcon notifyicon;
        public MainFrm()
        {
            InitializeComponent();

            g_Global = new Global();
            this.Icon = g_Global.ICON;
            this.Text = "莫莫的工具箱";
        }

        private void MainFrm_Load(object sender, EventArgs e)
        {
            ScreenHelper.LoadParam();
            this.WindowState = (FormWindowState)IniFileHelper.GetInt32Value("Main", "WindowState", g_Global.MainParam);
            ScreenHelper.ShowScreen(this, IniFileHelper.GetValue("Main", "TopMost", g_Global.MainParam) == "True");
            
            Utility.StartUpScreen w = new Utility.StartUpScreen();
            Thread t = new Thread(() =>
            {
                w.ShowDialog();
            });
            t.Start();

            g_Global.App = new FrameApplication(this);
            Dictionary<string, Type> PluginDic = g_Global.App.PluginManager.GetPluginTypes();
            Plugin p = null;
            foreach (string name in PluginDic.Keys)
            {
                p = g_Global.App.PluginManager.CreatePlugin(name);
            }
            addMenu();

            g_Global.App.PluginManager.load("layout.fm");//加载窗口布局
            timer1.Start();
            Thread.Sleep(1);
            w.CloseOnThread();//防止关闭时崩溃
            IniNotifyicon();

            //IsShow = !GetRegBootUpState();
            //ThisShow(sender, e);
            //cMenuBoolUp.Checked = GetRegBootUpState();
            //tsMenuTopMost.Text = FormHelper.SetFormTopMost(this, IniFileHelper.GetValue("Main", "TopMost", m_IniParam) == "True" ? true : false) ? "取消顶层" : "固定顶层";
            //tsMenuTopMost.Image = this.TopMost ? Properties.Resources.TopMostTrue : Properties.Resources.TopMostFalse;

            
            g_Global.App.OnInitialUiEvnet();//初始化所有窗口

            

        }
        /// <summary>
        /// 添加菜单
        /// </summary>
        private void addMenu()
        {
            this.MainMenu.Items.Clear();
            ToolStrip mainMenu = this.MainMenu;
            //固定添加的菜单
            ToolStripDropDownButton system = new ToolStripDropDownButton();

            system.Text = Frame.Menu.StatMenuList["SYSTEM"].txt;
            system.Image = Frame.Menu.StatMenuList["SYSTEM"].image;
            ToolStripDropDownButton reset = new ToolStripDropDownButton();
            reset.Text = Frame.Menu.StatMenuList["RESET"].txt;
            reset.Image = Frame.Menu.StatMenuList["RESET"].image;
            system.DropDownItems.Add(reset.Text, reset.Image, ResetToolStripMenuItem_Click);
            ToolStripDropDownButton turnOff = new ToolStripDropDownButton();
            turnOff.Text = Frame.Menu.StatMenuList["EXIT"].txt;
            turnOff.Image = Frame.Menu.StatMenuList["EXIT"].image;
            system.DropDownItems.Add(turnOff.Text, turnOff.Image, ExitToolStripMenuItem_Click);

            ToolStripDropDownButton sleep = new ToolStripDropDownButton();
            sleep.Text = Frame.Menu.StatMenuList["SLEEP"].txt;
            sleep.Image = Frame.Menu.StatMenuList["SLEEP"].image;
            system.DropDownItems.Add(sleep.Text, sleep.Image, SleepToolStripMenuItem_Click);

            ToolStripDropDownButton reBootOff = new ToolStripDropDownButton();
            reBootOff.Text = Frame.Menu.StatMenuList["BootOff"].txt;
            reBootOff.Image = Frame.Menu.StatMenuList["BootOff"].image;
            system.DropDownItems.Add(reBootOff.Text, reBootOff.Image, ReBootToolStripMenuItem_Click);

            ToolStripDropDownButton powerOff = new ToolStripDropDownButton();
            powerOff.Text = Frame.Menu.StatMenuList["PowerOff"].txt;
            powerOff.Image = Frame.Menu.StatMenuList["PowerOff"].image;
            system.DropDownItems.Add(powerOff.Text, powerOff.Image, PowerOffToolStripMenuItem_Click);
            mainMenu.Items.Add(system);


            foreach (Frame.Menu.tMenu menu in Frame.Menu.MenuList)
            {

                ToolStripDropDownButton btn = new ToolStripDropDownButton();
                btn.Text = menu.txt;
                btn.Image = menu.image;
                mainMenu.Items.Add(btn);
                foreach (Plugin win in g_Global.App.PluginManager.GetMenuList(menu.name))
                {
                    btn.DropDownItems.Add(win.Text, win.ToolBarIcon, showDockWindows);
                    if (win.InToolBar)
                        ToolBar.Items.Add(win.Text, win.ToolBarIcon, showDockWindows);
                }
            }

        }

        

        private void ResetToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("要重新启动应用程序嘛？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
            {
                ExitToolStripMenuItem_Click(null, null);
                System.Diagnostics.Process.Start(System.Reflection.Assembly.GetExecutingAssembly().Location);
            }
        }

        private void ExitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void SleepToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(this, "是否让计算机进入睡眠", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
                Frame.PowerManager.WindowsController.ExitWindows(PowerManager.RestartOptions.Hibernate, true);
        }

        private void ReBootToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(this, "是否重启计算机", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
                Frame.PowerManager.WindowsController.ExitWindows(PowerManager.RestartOptions.Reboot, true);
        }

        private void PowerOffToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(this, "是否关闭计算机", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
                Frame.PowerManager.WindowsController.ExitWindows(PowerManager.RestartOptions.PowerOff, true);
        }
        /// <summary>
        /// 显示窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void showDockWindows(object sender, EventArgs e)
        {
            string text = sender.ToString();
            Plugin win = g_Global.App.PluginManager.GetPluin(text);
            if (win != null)
            {
                win.Show();
                return;
            }
        }
        /// <summary>
        /// 窗口关闭时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainFrm_FormClosing(object sender, FormClosingEventArgs e)
        {
            timer1.Stop();
            if (g_Global.App != null)
            {
                //关闭时保存当前窗体的状态
                g_Global.App.PluginManager.save("layout.fm");//保存窗口布局
                g_Global.App.ApplicationManager.SaveXml();
                g_Global.App.PluginManager.CloseAllWindows();
                g_Global.App.OnEndEvent();
            }
        }
        /// <summary>
        /// 状态栏定时器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            tsslTimer.Text = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");

        }

        private void notifyIcon_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                notifyiconMenu.Show();
            }
        }


        private void notifyIcon_DoubleClick(object sender, MouseEventArgs e)
        {
            ThisShow(GetMenuItem("ShowItem"), null);
        }

        #region 任务栏小图标
        /// <summary>
        /// 初始化任务栏小图标菜单
        /// </summary>
        private void IniNotifyicon()
        {
            //任务栏小图标
            notifyicon = new NotifyIcon();
            notifyicon.Icon = this.Icon;
            notifyicon.Text = this.Text;
            notifyicon.BalloonTipText = "这是莫莫的工具箱";
            notifyicon.BalloonTipTitle = this.Text;
            notifyicon.ShowBalloonTip(5000);
            notifyicon.Visible = true;
            notifyicon.ContextMenuStrip = notifyiconMenu;
            notifyicon.MouseClick += new MouseEventHandler(notifyIcon_MouseClick);//鼠标单击
            notifyicon.MouseDoubleClick += new MouseEventHandler(notifyIcon_DoubleClick);//鼠标双击


            ToolStripMenuItem FavoriteItem = new ToolStripMenuItem("常用软件", Properties.Resources.Favorite);
            notifyiconMenu.Items.Add(FavoriteItem);
            foreach (AppClass appClass in g_Global.App.ApplicationManager.Application)
            {
                foreach(App app in appClass.AppList)
                {
                    if(app.Favorite)
                    {
                        
                        FavoriteItem.DropDownItems.Add(app.Name,File.Exists(app.Path) ? Icon.ExtractAssociatedIcon(app.Path).ToBitmap():null, RunApp);
                    }
                }
            }

            int number = ScreenHelper.GetScreenNumber();
            ToolStripMenuItem ScreenItem = new ToolStripMenuItem("显示器", Properties.Resources.screens_switch);
            notifyiconMenu.Items.Add(ScreenItem);
            for (int i=0;i<number;  i++)
            {
                ScreenItem.DropDownItems.Add(i.ToString(), Properties.Resources.电脑_显示屏_显示器, ShowScreen);
            }

            ToolStripMenuItem bootUpItem = new ToolStripMenuItem("开机启动", Properties.Resources.开机启动, BootUp);
            bootUpItem.Checked = GetRegBootUpState();
            notifyiconMenu.Items.Add(bootUpItem);

            ToolStripMenuItem TopMostItem = new ToolStripMenuItem("置顶", Properties.Resources.TopMostTrue, tsMenuTopMost_Click);
            TopMostItem.Checked = IniFileHelper.GetValue("Main", "TopMost", g_Global.MainParam) == "True";
            this.TopMost = TopMostItem.Checked;
            notifyiconMenu.Items.Add(TopMostItem);

            //ToolStripMenuItem ShowItem = new ToolStripMenuItem(IniFileHelper.GetValue("Main", "Show", g_Global.MainParam) == "False"? "显示" : "隐藏", IniFileHelper.GetValue("Main", "Show", g_Global.MainParam) == "False" ? Properties.Resources.Show: Properties.Resources.Hide, ThisShow);
            //ShowItem.Name = "ShowItem";
            //notifyiconMenu.Items.Add(ShowItem);
            //if (ShowItem.Text.CompareTo("显示") == 0) this.Hide();

            ToolStripMenuItem ComputerItem = new ToolStripMenuItem("计算机", Properties.Resources.计算机);
            ComputerItem.DropDownItems.Add("睡眠",Properties.Resources.Sleep, SleepToolStripMenuItem_Click);
            ComputerItem.DropDownItems.Add("重启", Properties.Resources.ReBoot, ReBootToolStripMenuItem_Click);
            ComputerItem.DropDownItems.Add("关机", Properties.Resources.PowerOff, PowerOffToolStripMenuItem_Click);
            notifyiconMenu.Items.Add(ComputerItem);

            ToolStripMenuItem systemItem = new ToolStripMenuItem("系统", Properties.Resources.System);
            systemItem.DropDownItems.Add("重启", Properties.Resources.Reset, ResetToolStripMenuItem_Click);
            systemItem.DropDownItems.Add("关闭", Properties.Resources.Close, ExitToolStripMenuItem_Click);
            notifyiconMenu.Items.Add(systemItem);
        }



        private void ThisShow(object sender, EventArgs e)
        {
            ToolStripMenuItem ShowItem = sender as ToolStripMenuItem;
            if (ShowItem.Text == "隐藏")
            {
                this.Hide();
                ShowItem.Text = "显示";
                ShowItem.Image = Properties.Resources.Show;
            }
            else
            {
                this.Show();
                this.WindowState = FormWindowState.Maximized;
                ShowItem.Text = "隐藏";
                ShowItem.Image = Properties.Resources.Hide;
                this.Focus();
                this.WindowState = FormWindowState.Normal;
            }
            IniFileHelper.SetValue("Main", "Show", ShowItem.Checked.ToString(), g_Global.MainParam);
        }

        private void tsMenuTopMost_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem TopMostItem = sender as ToolStripMenuItem;
            TopMostItem.Checked = !TopMostItem.Checked;
            IniFileHelper.SetValue("Main", "TopMost", TopMostItem.Checked.ToString(), g_Global.MainParam);
            this.TopMost = TopMostItem.Checked;
        }

        private void BootUp(object sender, EventArgs e)
        {
            ToolStripMenuItem bootUpItem = sender as ToolStripMenuItem;           
            SetRegBootUpValue(!bootUpItem.Checked);
            bootUpItem.Checked = GetRegBootUpState();
        }

        private void ShowScreen(object sender, EventArgs e)
        {
            int index = Convert.ToInt32(sender.ToString());
            ScreenHelper.ShowScreen(this, IniFileHelper.GetValue("Main", "TopMost", g_Global.MainParam) == "True", index);
            IniFileHelper.SetValue("Main", "Screen", index, g_Global.MainParam);
        }

        private void RunApp(object sender, EventArgs e)
        {
            ToolStripDropDownItem item = sender as ToolStripDropDownItem;
            
            string path = g_Global.App.ApplicationManager.GetApp(item.Text).Path;
            if (File.Exists(path))
                Frame.DirectoryHelper.RunExe(path);
        }

        private ToolStripMenuItem GetMenuItem(string name)
        {
            ToolStripMenuItem item = null;
            for(int i=0; i<notifyiconMenu.Items.Count; i++)
            {
                if(notifyiconMenu.Items[i].Name == name)
                {
                    item = (ToolStripMenuItem)notifyiconMenu.Items[i];
                    break;
                }
            }
            return item;
        }

        #endregion


        #region 注册表
        private bool GetRegBootUpState()
        {
            string FullPath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run";
            return RegistryHelper.IsRegistryFolderExist(FullPath, "MTools");
        }

        private void SetRegBootUpValue(bool en)
        {
            string appPath = System.Windows.Forms.Application.ExecutablePath;
            string FullPath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run";
            if (en)
            {
                en = RegistryHelper.CreateOrSetRegistryKey(FullPath, "MTools", appPath);
            }
            else
            {
                en = RegistryHelper.DelRegistryKey(FullPath, "MTools");
            }
            //cMenuBoolUp.Checked = GetRegBootUpState();
        }



        #endregion
    }
}
